package com.yu.service.impl;

import com.alibaba.fastjson.JSON;
import com.yu.dao.DeptMapper;
import com.yu.dao.EmpMapper;
import com.yu.pojo.Dept;
import com.yu.pojo.Result;
import com.yu.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public String findAllDept() {
        List<Dept> depts = deptMapper.selectAll();
        Result success = Result.success(depts);
        return JSON.toJSONString(success);
    }

//    TODO:spring事务的注解
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String removeById(Integer id) {
        int row = deptMapper.deleteById(id);
//        int i = 10 / 0;
        empMapper.deleteByDeptId(id);
        Result result = null;
        if (row > 0){
            result = Result.success();
        }else{
            result = Result.error("删除失败");
        }
        return JSON.toJSONString(result);
    }

    @Override
    public String addDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        int row = deptMapper.insertDept(dept);

        Result result = null;
        if (row > 0){
            result = Result.success();
        }else{
            result = Result.error("添加失败");
        }
        return JSON.toJSONString(result);
    }

    @Override
    public String findByIdDept(Integer id) {
        Dept dept = deptMapper.findById(id);
        Result success = Result.success(dept);
        return JSON.toJSONString(success);
    }

    @Override
    public String updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        int row = deptMapper.updateDept(dept);

        Result result = null;
        if (row > 0){
            result = Result.success();
        }else{
            result = Result.error("修改失败");
        }
        return JSON.toJSONString(result);
    }
}
